//
//  DMInAppPurchaseManager.m
//  DualMediationSDK
//
//  Created by 叶佳瑞 on 2024/12/19.
//

#import "DMInAppPurchaseManager.h"
#import "DMInAppPurchaseManager+private.h"
#import "../Adjust/IMAdjustService.h"
#import "DMInAppPurchaseHandleManager.h"
#import "DMInAppVerifyManager.h"
#import "../../Core/DMLifecycle/Types/DMPurchaseInfo.h"
#import "../../Utils/Logger/IMLogUtils.h"
#import <StoreKit/StoreKit.h>
#if __has_include(<UIKit/UIKit.h>)
#import <UIKit/UIKit.h>
#define UIKIT_AVAILABLE 1
#else
#define UIKIT_AVAILABLE 0
#endif
#import "../../Utils/Device/IMKeychainUUIDManager.h"
#import "../TA/DMThinkingManager.h"
#import "../../Utils/JSON/DMConfigReader.h"

// Adjust SDK 可用性保护
#if __has_include(<AdjustSdk/AdjustSdk.h>)
#import <AdjustSdk/AdjustSdk.h>
#define ADJUST_SDK_AVAILABLE 1
#else
#define ADJUST_SDK_AVAILABLE 0
#endif

static NSString *KSandboxReceipt = @"sandboxReceipt";
static NSString *kSANDBOX = @"SANDBOX";
static NSString *kAppStore = @"AppStore";

@interface DMInAppPurchaseManager()<SKPaymentTransactionObserver, SKProductsRequestDelegate>

@property (nonatomic, assign) BOOL isRestore;
@property (nonatomic, strong) NSString *currentProductId;
@property (nonatomic, strong) NSMutableDictionary *productTypeCache; // 缓存商品类型
@property (nonatomic, strong) NSMutableSet *duplicateTransactions; // 添加重复交易记录集合
@property (nonatomic, assign) BOOL isRestoreInProgress; // 添加恢复购买进行中的标志
@property (nonatomic, strong) NSMutableSet *restoredProductIds; // 记录已恢复的商品ID
@property (nonatomic, assign) BOOL isFullRestoreInProgress; // 全量恢复购买进行中的标志
@property (nonatomic, assign) BOOL isReuse;

@end

@implementation DMInAppPurchaseManager
{
    NSInteger verifyCount;
    BOOL isGetList;
    int _isResume;
    NSString *_productId;
}

static DMInAppPurchaseManager *_InAppPurchaseManager = nil;
+ (instancetype)shareInAppPurchaseManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _InAppPurchaseManager = [[self alloc] init];
        [[SKPaymentQueue defaultQueue] addTransactionObserver:_InAppPurchaseManager];
    });
    return _InAppPurchaseManager;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _productTypeCache = [NSMutableDictionary dictionary];
        _duplicateTransactions = [NSMutableSet set];
        _isRestoreInProgress = NO;
        _restoredProductIds = [NSMutableSet set];
        _isFullRestoreInProgress = NO;
        _isReuse = NO;
    }
    return self;
}

- (void)launchInAppPurchase:(NSString *)productId {
    // Billing_purchase_request 内购请求事件打点
    NSDictionary *billingPurchaseRequestParams = @{
        @"w_product_id": productId ?: @"",
        @"w_is_restore": @0
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_purchase_request" properties:billingPurchaseRequestParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_purchase_request - 开始内购请求，商品ID: %@", productId];
    
    // 调用购买开始回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didBeginInAppPurchase:)]) {
        [self.delegate dmAdManager:nil didBeginInAppPurchase:productId];
    }
    
    _isResume = 0;
    _productId = productId;
    
    // 检查商品类型
    DMProductType productType = [self getProductType:productId];
    
    // 如果是非消耗型商品，检查是否已购买
    if (productType == DMProductTypeNonConsumable && [self isProductPurchased:productId]) {
        // 调用购买成功回调
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessInAppPurchase:transactionId:)]) {
            [self.delegate dmAdManager:nil didSuccessInAppPurchase:productId transactionId:@"restored"];
        }
        return;
    }
    
    if ([SKPaymentQueue canMakePayments]) {
        [self requestProductData:productId];
    } else {
        // 调用购买失败回调
        NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-1 userInfo:@{NSLocalizedDescriptionKey: @"不允许程序内付费"}];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailInAppPurchase:error:)]) {
            [self.delegate dmAdManager:nil didFailInAppPurchase:productId error:error];
        }
    }
}

- (void)restoreInAppPurchase:(NSString *)productId {
    BOOL isFullRestore = (productId == nil || productId.length == 0);
    
    // Billing_purchase_request 恢复购买请求事件打点
    NSDictionary *billingPurchaseRequestParams = @{
        @"w_product_id": productId ?: @"",
        @"w_is_restore": @1
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_purchase_request" properties:billingPurchaseRequestParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_purchase_request - 开始恢复购买请求，商品ID: %@", productId ?: @"全量恢复"];
    
    // 调用恢复购买开始回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didBeginRestoreInAppPurchase:)]) {
        [self.delegate dmAdManager:nil didBeginRestoreInAppPurchase:productId];
    }
    
    // 防止多次点击恢复购买
    if (self.isRestoreInProgress || (isFullRestore && self.isFullRestoreInProgress)) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 恢复购买正在进行中，请勿重复操作"];
        // 调用恢复购买失败回调
        NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-2 userInfo:@{NSLocalizedDescriptionKey: @"恢复购买正在进行中，请勿重复操作"}];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailRestoreInAppPurchase:error:)]) {
                     [self.delegate dmAdManager:nil didFailRestoreInAppPurchase:productId error:error];
        }
        return;
    }
    
    // 如果是指定商品恢复，检查该商品是否已经恢复过（包括持久化记录检查）
    if (!isFullRestore) {
        // 检查会话中的记录
        if ([self.restoredProductIds containsObject:productId]) {
            [IMLogUtils info:IMLogTagIAP format:@"商品 %@ 在本次会话中已恢复过，无需重复恢复", productId];
            // 调用恢复购买失败回调
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-3 userInfo:@{NSLocalizedDescriptionKey: @"商品已恢复过"}];
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailRestoreInAppPurchase:error:)]) {
            [self.delegate dmAdManager:nil didFailRestoreInAppPurchase:productId error:error];
            }
            return;
        }
        
        // 检查持久化记录（针对非消耗型商品）
        if ([self getProductType:productId] == DMProductTypeNonConsumable) {
            // 检查是否已经通过恢复获得过
            if ([self isProductRestored:productId]) {
                [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 在此次安装中已恢复过，无需重复恢复", productId];
                // 调用恢复购买失败回调
                NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-4 userInfo:@{NSLocalizedDescriptionKey: @"该商品在此次安装中已恢复过"}];
                if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailRestoreInAppPurchase:error:)]) {
            [self.delegate dmAdManager:nil didFailRestoreInAppPurchase:productId error:error];
                }
                return;
            }
            
            // 检查是否已经通过购买获得过
            if ([self isProductPurchased:productId]) {
                [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 已通过购买获得，无需恢复", productId];
                // 调用恢复购买失败回调
                NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-5 userInfo:@{NSLocalizedDescriptionKey: @"该商品已通过购买获得，无需恢复"}];
                if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailRestoreInAppPurchase:error:)]) {
            [self.delegate dmAdManager:nil didFailRestoreInAppPurchase:productId error:error];
                }
                return;
            }
        }
    }
    
    // 设置恢复购买状态为进行中
    if (isFullRestore) {
        self.isFullRestoreInProgress = YES;
        [IMLogUtils info:IMLogTagIAP format:@"开始全量恢复购买"];
    } else {
        self.isRestoreInProgress = YES;
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 开始恢复单个商品: %@", productId];
    }
    
    // 使用DMLifecycleManager的购买开始回调
    // 注意：DMLifecycleManager没有直接的恢复购买开始回调，可以通过其他方式处理
    // 或者在恢复成功/失败时调用相应回调
    _isResume = 1;
    _productId = productId ?: @"";
    
    // 清除所有重复订单标记
    [self.duplicateTransactions removeAllObjects];
    
    // 如果是指定的非消耗型商品，清除本地记录
    if (!isFullRestore && [self getProductType:productId] == DMProductTypeNonConsumable) {
        [self clearPurchaseRecord:productId];
    }
    
    // 如果是全量恢复，可以选择清除所有非消耗型商品的本地记录
    if (isFullRestore) {
        // 这里可以根据需要决定是否清除所有记录
        // [self clearAllNonConsumablePurchaseRecords];
    }
    
    // 清除已验证交易记录
    [[DMInAppVerifyManager sharedManager] clearVerifiedTransactions];
    
    // 开始恢复购买
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}

- (void)paymentQueueRestoreCompletedTransactionsFinished:(SKPaymentQueue *)queue {
    _isResume = 0; // 重置恢复购买状态
    self.isRestoreInProgress = NO; // 重置恢复购买进行中的标志
    self.isFullRestoreInProgress = NO; // 重置全量恢复购买进行中的标志
    
    // SDK_iap_restore_success 内购恢复成功事件打点
    NSDictionary *iapRestoreSuccessParams = @{
        @"w_restored_count": @(self.restoredProductIds.count),
        @"w_restored_products": [self.restoredProductIds.allObjects componentsJoinedByString:@","]
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_iap_restore_success" properties:iapRestoreSuccessParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: SDK_iap_restore_success - 恢复购买成功，恢复商品数量: %lu", (unsigned long)self.restoredProductIds.count];
    
    // 使用DMAdDelegate的恢复购买成功回调
    if (_isReuse == NO) {
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessRestoreInAppPurchase:transactionId:)]) {
            [self.delegate dmAdManager:nil didSuccessRestoreInAppPurchase:_productId transactionId:@"restored"];
        }
    } else {
        NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-6 userInfo:@{NSLocalizedDescriptionKey: @"恢复购买重复"}];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailRestoreInAppPurchase:error:)]) {
            [self.delegate dmAdManager:nil didFailRestoreInAppPurchase:_productId error:error];
        }
    }
}

- (void)paymentQueue:(SKPaymentQueue *)paymentQueue restoreCompletedTransactionsFailedWithError:(NSError *)error {
    _isResume = 0; // 重置恢复购买状态
    self.isRestoreInProgress = NO; // 重置恢复购买进行中的标志
    self.isFullRestoreInProgress = NO; // 重置全量恢复购买进行中的标志
    
    // SDK_iap_restore_fail 内购恢复失败事件打点
    NSDictionary *iapRestoreFailParams = @{
        @"w_error_code": @(error.code),
        @"w_error_message": error.localizedDescription ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_iap_restore_fail" properties:iapRestoreFailParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: SDK_iap_restore_fail - 恢复购买失败，错误信息: %@", error.localizedDescription];
    
    // 使用DMAdDelegate的恢复购买失败回调
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailRestoreInAppPurchase:error:)]) {
        [self.delegate dmAdManager:nil didFailRestoreInAppPurchase:_productId error:error];
    }
}

- (void)removeObserver {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)requestProductLists:(NSArray *)array {
    isGetList = YES;
    NSSet *nsset = [NSSet setWithArray:array];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}

- (void)requestProductData:(NSString *)type {
    isGetList = NO;
    NSArray *product = @[type];
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    verifyCount = 0;
    NSArray *product = response.products;
    [DMInAppPurchaseHandleManager shareInAppPurchaseHandleManager].productIds = product;
    if (product.count == 0) {
        // Billing_order_create_status 订单创建失败事件打点
        NSDictionary *billingOrderCreateStatusParams = @{
            @"w_product_id": _productId ?: @"",
            @"w_is_success": @NO,
            @"w_order_p_id": @"",
            @"w_is_restore": @(_isResume == 1 ? 1 : 0),
            @"w_error_code": @"-7",
            @"w_error_msg": @"没有商品"
        };
        [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_order_create_status" properties:billingOrderCreateStatusParams];
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_order_create_status - 订单创建失败，没有商品"];
        
        if (isGetList) {
            // 调用商品列表获取失败回调
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-7 userInfo:@{NSLocalizedDescriptionKey: @"没有商品"}];
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToReceiveProductList:)]) {
                 [self.delegate dmAdManager:nil didFailToReceiveProductList:error];
            }
        } else {
            // 使用DMAdDelegate的购买失败回调
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-7 userInfo:@{NSLocalizedDescriptionKey: @"没有商品"}];
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailInAppPurchase:error:)]) {
                [self.delegate dmAdManager:nil didFailInAppPurchase:_productId error:error];
            }
        }
        return;
    }
    
    SKProduct *p = nil;
    NSMutableArray *array = [NSMutableArray array];
    for (SKProduct *pro in product) {
        [array addObject:pro];
        if ([pro.productIdentifier isEqualToString:_productId]) {
            p = pro;
        }
    }
    
    if (isGetList) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 商品列表获取成功，商品数量: %lu", (unsigned long)array.count];
        [DMInAppPurchaseHandleManager shareInAppPurchaseHandleManager].productIds = [array copy];
        
        // 调用商品列表获取成功回调（传递不可变副本，避免外部在遍历时修改导致崩溃）
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didReceiveProductList:)]) {
            [self.delegate dmAdManager:nil didReceiveProductList:[array copy]];
        }
    } else {
        if (p) {
            // 检查商品类型
            DMProductType productType = [self getProductType:p.productIdentifier];
            
            // 如果是非消耗型商品，再次检查是否已购买
            if (productType == DMProductTypeNonConsumable && [self isProductPurchased:p.productIdentifier]) {
                // Billing_order_create_status 订单创建失败事件打点（商品已购买）
                NSDictionary *billingOrderCreateStatusParams = @{
                    @"w_product_id": p.productIdentifier ?: @"",
                    @"w_is_success": @NO,
                    @"w_order_p_id": @"",
                    @"w_is_restore": @(_isResume == 1 ? 1 : 0),
                    @"w_error_code": @"-8",
                    @"w_error_msg": @"该商品已购买"
                };
                [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_order_create_status" properties:billingOrderCreateStatusParams];
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_order_create_status - 订单创建失败，该商品已购买"];
                
                // 使用DMLifecycleManager的购买失败回调
                if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailInAppPurchase:error:)]) {
                NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-8 userInfo:@{NSLocalizedDescriptionKey: @"该商品已购买", @"type": @"already_purchased"}];
                [self.delegate dmAdManager:nil didFailInAppPurchase:p.productIdentifier error:error];
            }
                return;
            }
            
            // Billing_order_create_status 订单创建成功事件打点
            NSDictionary *billingOrderCreateStatusParams = @{
                @"w_product_id": p.productIdentifier ?: @"",
                @"w_is_success": @YES,
                @"w_order_p_id": p.productIdentifier, // iOS使用商品ID作为订单标识
                @"w_is_restore": @(_isResume == 1 ? 1 : 0),
                @"w_error_code": @"",
                @"w_error_msg": @""
            };
            [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_order_create_status" properties:billingOrderCreateStatusParams];
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_order_create_status - 订单创建成功，商品ID: %@", p.productIdentifier];
            
            SKPayment *payment = [SKPayment paymentWithProduct:p];
            [[SKPaymentQueue defaultQueue] addPayment:payment];
        } else {
            // Billing_order_create_status 订单创建失败事件打点（商品信息获取失败）
            NSDictionary *billingOrderCreateStatusParams = @{
                @"w_product_id": _productId ?: @"",
                @"w_is_success": @NO,
                @"w_order_p_id": @"",
                @"w_is_restore": @(_isResume == 1 ? 1 : 0),
                @"w_error_code": @"-9",
                @"w_error_msg": @"商品信息获取失败"
            };
            [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_order_create_status" properties:billingOrderCreateStatusParams];
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_order_create_status - 订单创建失败，商品信息获取失败"];
            
            // 使用DMAdDelegate的购买失败回调
            NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-9 userInfo:@{NSLocalizedDescriptionKey: @"商品信息获取失败", @"type": @"product_info_failed"}];
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailInAppPurchase:error:)]) {
                [self.delegate dmAdManager:nil didFailInAppPurchase:_productId error:error];
            }
        }
    }
}

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error {
    if (isGetList) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 商品列表获取失败: %@", error.localizedDescription];
        // 调用商品列表获取失败回调
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailToReceiveProductList:)]) {
            [self.delegate dmAdManager:nil didFailToReceiveProductList:error];
        }
    }
}
- (void)requestDidFinish:(SKRequest *)request {}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    for (SKPaymentTransaction *tran in transactions) {
        NSString *transactionId = tran.originalTransaction.transactionIdentifier ?: tran.transactionIdentifier;
        NSString *productId = tran.payment.productIdentifier;
        DMProductType productType = [self getProductType:productId];
        
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 交易更新: %@ - 状态: %ld - 商品ID: %@", transactionId, (long)tran.transactionState, productId];
        
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased: {
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 交易购买成功: %@ - 商品ID: %@", transactionId, productId];
                // 检查是否是重复交易
                if ([self.duplicateTransactions containsObject:transactionId]) {
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                    // 如果是非消耗型商品，返回成功回调
                    if (productType == DMProductTypeNonConsumable) {
                        // 调用购买成功回调
                        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessInAppPurchase:transactionId:)]) {
                            [self.delegate dmAdManager:nil didSuccessInAppPurchase:productId transactionId:transactionId];
                        }
                    } else {
                        // 调用购买失败回调
                        NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:-6 userInfo:@{NSLocalizedDescriptionKey: @"订单重复，请勿重复购买"}];
                        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessInAppPurchase:transactionId:)]) {
                            [self.delegate dmAdManager:nil didSuccessInAppPurchase:productId transactionId:transactionId];
                        }
                    }
                    break;
                }
                
                // 检查非消耗型商品是否已购买
                if (productType == DMProductTypeNonConsumable && [self isProductPurchased:productId]) {
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                    
                    // 调用购买成功回调
                    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessInAppPurchase:transactionId:)]) {
                        [self.delegate dmAdManager:nil didSuccessInAppPurchase:productId transactionId:transactionId];
                    }
                    break;
                }
                
                // 对于非消耗型商品，在开始处理购买前就标记到会话记录中
                // 这样可以防止购买完成后立即恢复购买导致重复发放
                if (productType == DMProductTypeNonConsumable && !_isResume) {
                    [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 开始购买处理，预先标记到会话记录", productId];
                    [self.restoredProductIds addObject:productId];
                }
                
                if ([[DMInAppVerifyManager sharedManager] isPendingOrderTransactionId:transactionId]) {
                    [self uploadReceiptForTransaction:tran];
                } else {
                    [self uploadReceiptForTransaction:tran];
                }
                break;
            }
            case SKPaymentTransactionStateFailed: {
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 交易失败: %@ - 错误码: %ld - 商品ID: %@", tran.error.localizedDescription, (long)tran.error.code, productId];
                [self handleFailed:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                break;
            }
            case SKPaymentTransactionStateRestored: {
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 交易恢复成功: %@ - 商品ID: %@", transactionId, productId];
                // 检查该商品是否已经在本次会话中恢复过
                if ([self.restoredProductIds containsObject:productId]) {
                    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 商品 %@ 在本次会话中已恢复过，跳过重复处理", productId];
                    _isReuse = YES;
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                    break;
                }
                
                // 检查非消耗型商品是否已经获得过（通过恢复或购买）
                if (productType == DMProductTypeNonConsumable) {
                    // 检查是否已经通过恢复获得过
                    if ([self isProductRestored:productId]) {
                        [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 在此次安装中已恢复过，跳过重复处理", productId];
                        _isReuse = YES;
                        [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                        break;
                    }
                    
                    // 检查是否已经通过购买获得过
                    if ([self isProductPurchased:productId]) {
                        [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 已通过购买获得，跳过恢复处理", productId];
                        _isReuse = YES;
                        [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                        break;
                    }
                }
                
                // 恢复购买时，如果是非消耗型商品，清除重复标记并保存购买记录
                if (productType == DMProductTypeNonConsumable) {
                    [self clearDuplicateTransaction:transactionId];
                    [self savePurchaseRecord:productId];
                    
                    // 将商品添加到已恢复列表中（会话记录）
                    [self.restoredProductIds addObject:productId];
                    
                    // 保存已恢复记录（持久化记录）
                    [self saveRestoredRecord:productId];
                    
                    // 如果是恢复购买流程，发送成功回调
                    if (_isResume) {
                        // 调用恢复购买成功回调
                        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessRestoreInAppPurchase:transactionId:)]) {
                            [self.delegate dmAdManager:nil didSuccessRestoreInAppPurchase:productId transactionId:transactionId];
                        }
                    }
                } else {
                    // 消耗型商品也记录到会话中，防止在本次会话中重复发放
                    [self.restoredProductIds addObject:productId];
                }
                
                if ([[DMInAppVerifyManager sharedManager] isPendingOrderTransactionId:transactionId]) {
                    [self uploadReceiptForTransaction:tran];
                } else {
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                }
                break;
            }
            case SKPaymentTransactionStatePurchasing:
                break;
            default:
                break;
        }
    }
}

- (void)errorReason:(SKPaymentTransaction *)tran{
    NSError *error = tran.error;
    NSString *detail;
    if (error != nil) {
        switch (error.code) {
            case SKErrorUnknown:
                [IMLogUtils error:IMLogTagError format:@"SKErrorUnknown"];
                detail = @"未知的错误，您可能正在使用越狱手机";
                break;
            case SKErrorClientInvalid:
                [IMLogUtils error:IMLogTagError format:@"SKErrorClientInvalid"];
                detail = @"当前苹果账户无法购买商品(如有疑问，可以询问苹果客服)";
                break;
            case SKErrorPaymentCancelled:
                [IMLogUtils error:IMLogTagError format:@"SKErrorPaymentCancelled"];
                detail = @"订单已取消";
                break;
            case SKErrorPaymentInvalid:
                [IMLogUtils error:IMLogTagError format:@"SKErrorPaymentInvalid"];
                detail = @"订单无效(如有疑问，可以询问苹果客服)";
                break;
            case SKErrorPaymentNotAllowed:
                [IMLogUtils error:IMLogTagError format:@"SKErrorPaymentNotAllowed"];
                detail = @"当前苹果设备无法购买商品(如有疑问，可以询问苹果客服)";
                break;
            case SKErrorStoreProductNotAvailable:
                [IMLogUtils error:IMLogTagError format:@"SKErrorStoreProductNotAvailable"];
                detail = @"当前商品不可用";
                break;
            default:
                [IMLogUtils error:IMLogTagError format:@"No Match Found for error"];
                detail = @"未知错误";
                break;
        }
    }

    // 调用购买失败回调
    NSError *purchaseError = [NSError errorWithDomain:@"DMInAppPurchase" code:error.code userInfo:@{NSLocalizedDescriptionKey: detail}];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailInAppPurchase:error:)]) {
        [self.delegate dmAdManager:nil didFailInAppPurchase:tran.payment.productIdentifier ?: @"" error:purchaseError];
    }
}

- (void)uploadReceiptForTransaction:(SKPaymentTransaction *)transaction {
    NSURL *receiptUrl = [[NSBundle mainBundle] appStoreReceiptURL];
    NSData *receiptData = [NSData dataWithContentsOfURL:receiptUrl];
    NSString *receiptString = [receiptData base64EncodedStringWithOptions:0];
    NSString *originalTransactionId = transaction.originalTransaction ? transaction.originalTransaction.transactionIdentifier : transaction.transactionIdentifier;
    NSString *productId = transaction.payment.productIdentifier ?: @"";
    DMProductType productType = [self getProductType:productId];

    if (receiptString.length == 0 || productId.length == 0) return;

    NSString *receiptPath = receiptUrl.path;
    NSString *envType = [receiptPath containsString:KSandboxReceipt] ? kSANDBOX : kAppStore;

    // 如果是非消耗型商品，先清除重复标记
    if (productType == DMProductTypeNonConsumable) {
        [self clearDuplicateTransaction:originalTransactionId];
    }

    // 使用系统UUID替代WDKeychain
    NSString *uuid = [IMKeychainUUIDManager getOrCreateLoginUUID];
    [[DMInAppVerifyManager sharedManager] verifyTransactionWithTransactionId:originalTransactionId
                                                                   productId:productId
                                                                        uuid:uuid
                                                                     envType:envType];
}

- (void)completeTransactionWithTransactionId:(NSString *)transactionId productId:(NSString *)productId receiptType:(NSString *)receiptType {
    // 用于防重的成功上报集合（函数级静态）
    static NSMutableSet *reportedPurchaseSuccessTransactions;
    if (!reportedPurchaseSuccessTransactions) { reportedPurchaseSuccessTransactions = [NSMutableSet set]; }
    // 如果是恢复购买的商品，检查是否已经发放过奖励
    if (_isResume) {
        // 检查会话记录
        if ([self.restoredProductIds containsObject:productId]) {
            [IMLogUtils info:IMLogTagIAP format:@"商品 %@ 在本次会话的恢复购买过程中已发放过奖励，跳过重复发放", productId];
            // 仍然需要完成交易
            for (SKPaymentTransaction *tran in [SKPaymentQueue defaultQueue].transactions) {
                NSString *currentId = tran.originalTransaction.transactionIdentifier ?: tran.transactionIdentifier;
                if ([currentId isEqualToString:transactionId]) {
                    [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                    return;
                }
            }
            return;
        }
        
        // 检查非消耗型商品是否已经获得过（通过恢复或购买）
        if ([self getProductType:productId] == DMProductTypeNonConsumable) {
            // 检查是否已经通过恢复获得过
            if ([self isProductRestored:productId]) {
                [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 在此次安装中已恢复过，跳过重复发放", productId];
                // 仍然需要完成交易
                for (SKPaymentTransaction *tran in [SKPaymentQueue defaultQueue].transactions) {
                    NSString *currentId = tran.originalTransaction.transactionIdentifier ?: tran.transactionIdentifier;
                    if ([currentId isEqualToString:transactionId]) {
                        [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                        return;
                    }
                }
                return;
            }
            
            // 检查是否已经通过购买获得过
            if ([self isProductPurchased:productId]) {
                [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 已通过购买获得，跳过恢复发放", productId];
                // 仍然需要完成交易
                for (SKPaymentTransaction *tran in [SKPaymentQueue defaultQueue].transactions) {
                    NSString *currentId = tran.originalTransaction.transactionIdentifier ?: tran.transactionIdentifier;
                    if ([currentId isEqualToString:transactionId]) {
                        [[SKPaymentQueue defaultQueue] finishTransaction:tran];
                        return;
                    }
                }
                return;
            }
        }
    }
    
    for (SKPaymentTransaction *tran in [SKPaymentQueue defaultQueue].transactions) {
        NSString *currentId = tran.originalTransaction.transactionIdentifier ?: tran.transactionIdentifier;
        if ([currentId isEqualToString:transactionId]) {
            [self computeInpurchaseReceipt_type:receiptType productId:productId transaction_id:transactionId];
            
            // SDK_iap_success 内购成功事件打点
            NSDictionary *iapSuccessParams = @{
                @"w_product_id": productId ?: @"",
                @"w_product_type": [self getProductTypeString:productId],
                @"w_transaction_id": transactionId ?: @"",
                @"w_receipt_type": receiptType ?: @""
            };
            [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_iap_success" properties:iapSuccessParams];
            [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: SDK_iap_success - 交易完成，交易ID: %@", transactionId];
            
                            // 保存非消耗型商品的购买记录
                if ([self getProductType:productId] == DMProductTypeNonConsumable) {
                    [self savePurchaseRecord:productId];
                    [self clearDuplicateTransaction:transactionId];
                    
                    // 如果是恢复购买流程，记录已恢复的商品
                    if (_isResume) {
                        [self.restoredProductIds addObject:productId];
                        [self saveRestoredRecord:productId];
                    } else {
                        // 如果是正常购买流程，也要标记为已获得，防止后续恢复购买重复发放
                        [IMLogUtils info:IMLogTagIAP format:@"非消耗型商品 %@ 通过购买获得，标记为已获得状态", productId];
                        // 注意：这里不调用saveRestoredRecord，因为这不是恢复购买
                        // 但我们可以在会话中记录，防止同一会话内立即恢复
                        [self.restoredProductIds addObject:productId];
                    }
                } else if (_isResume) {
                    // 消耗型商品在恢复购买时也记录到会话中
                    [self.restoredProductIds addObject:productId];
                }
            
            // Billing_purchase_success 渠道回调成功事件打点（去重）
            static NSMutableSet *reportedPurchaseSuccessTransactions;
            if (!reportedPurchaseSuccessTransactions) { reportedPurchaseSuccessTransactions = [NSMutableSet set]; }
            if (transactionId.length > 0 && [reportedPurchaseSuccessTransactions containsObject:transactionId]) {
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] Billing_purchase_success 已上报，跳过重复: tx=%@", transactionId];
            } else {
                NSDictionary *billingPurchaseSuccessParams = @{
                    @"w_product_id": productId ?: @"",
                    @"w_order_p_id": productId, // iOS使用商品ID作为订单标识
                    @"w_is_restore": @(_isResume == 1 ? 1 : 0)
                };
                [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_purchase_success" properties:billingPurchaseSuccessParams];
                [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_purchase_success - 渠道回调成功，商品ID: %@", productId];
                if (transactionId.length > 0) { [reportedPurchaseSuccessTransactions addObject:transactionId]; }
            }
            
            // Billing_Revenue 内购收入事件打点
            [self trackBillingRevenueEvent:productId transactionId:transactionId isRestore:(_isResume == 1)];
            
            // 调用购买成功回调
            if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessInAppPurchase:transactionId:)]) {
                [self.delegate dmAdManager:nil didSuccessInAppPurchase:productId transactionId:transactionId];
            }
            [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            return;
        }
    }

    // Fallback: no matching transaction found in queue (e.g., server-verified or retry flows)
    // Still perform success handling and notify delegate to avoid missing callbacks.
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 未在队列中找到交易，触发成功回调: product=%@, tx=%@", productId ?: @"", transactionId ?: @""];

    // Billing_purchase_success 渠道回调成功事件打点 (fallback，去重)
    if (transactionId.length > 0 && [reportedPurchaseSuccessTransactions containsObject:transactionId]) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] Billing_purchase_success (fallback) 已上报，跳过重复: tx=%@", transactionId];
    } else {
        NSDictionary *billingPurchaseSuccessParams = @{
            @"w_product_id": productId ?: @"",
            @"w_order_p_id": productId, // iOS使用商品ID作为订单标识
            @"w_is_restore": @(_isResume == 1 ? 1 : 0)
        };
        [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_purchase_success" properties:billingPurchaseSuccessParams];
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_purchase_success (fallback) - 渠道回调成功，商品ID: %@", productId];
        if (transactionId.length > 0) { [reportedPurchaseSuccessTransactions addObject:transactionId]; }
    }

    // Billing_Revenue 内购收入事件打点 (fallback)
    [self trackBillingRevenueEvent:productId transactionId:transactionId isRestore:(_isResume == 1)];

    // 记录打点（与正常路径保持一致）
    NSDictionary *iapSuccessParams = @{
        @"w_product_id": productId ?: @"",
        @"w_product_type": [self getProductTypeString:productId],
        @"w_transaction_id": transactionId ?: @"",
        @"w_receipt_type": receiptType ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_iap_success" properties:iapSuccessParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: SDK_iap_success (fallback) - 交易ID: %@", transactionId ?: @""];

    // 尝试进行购买记录及重复处理的同步（非消耗型）
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        [self savePurchaseRecord:productId];
        // 恢复流程时，记录恢复信息
        if (_isResume) {
            [self.restoredProductIds addObject:productId];
            [self saveRestoredRecord:productId];
        } else {
            [self.restoredProductIds addObject:productId];
        }
    } else if (_isResume) {
        // 消耗型在恢复流程中记录到会话，防止重复
        [self.restoredProductIds addObject:productId];
    }

    // 触发成功回调（即使没有SKPaymentTransaction对象）
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessInAppPurchase:transactionId:)]) {
        [self.delegate dmAdManager:nil didSuccessInAppPurchase:productId transactionId:transactionId ?: @""];
    }
}

- (void)handleFailed:(SKPaymentTransaction *)transaction {
    NSString *msg = transaction.error.code == SKErrorPaymentCancelled ? @"用户取消交易" : @"交易失败";
    
    // Billing_purchase_failed 渠道回调失败事件打点
    NSString *errorType = @"";
    switch (transaction.error.code) {
        case SKErrorPaymentCancelled:
            errorType = @"user_cancelled";
            break;
        case SKErrorPaymentInvalid:
            errorType = @"payment_invalid";
            break;
        case SKErrorPaymentNotAllowed:
            errorType = @"payment_not_allowed";
            break;
        case SKErrorClientInvalid:
            errorType = @"client_invalid";
            break;
        case SKErrorUnknown:
        default:
            errorType = @"unknown";
            break;
    }
    
    NSDictionary *billingPurchaseFailedParams = @{
        @"w_product_id": transaction.payment.productIdentifier ?: @"",
        @"w_error_type": errorType,
        @"w_error_code": @(transaction.error.code).stringValue,
        @"w_error_msg": msg ?: @""
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_purchase_failed" properties:billingPurchaseFailedParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_purchase_failed - 渠道回调失败，商品ID: %@, 错误类型: %@", transaction.payment.productIdentifier ?: @"", errorType];
    
    // SDK_iap_fail 内购失败事件打点
    NSDictionary *iapFailParams = @{
        @"w_product_id": transaction.payment.productIdentifier ?: @"",
        @"w_product_type": [self getProductTypeString:transaction.payment.productIdentifier],
        @"w_error_message": msg ?: @"",
        @"w_error_code": @(transaction.error.code)
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"SDK_iap_fail" properties:iapFailParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: SDK_iap_fail - 商品ID: %@, 错误: %@", transaction.payment.productIdentifier ?: @"", msg];
    
    // 调用购买失败回调
    NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:transaction.error.code userInfo:@{NSLocalizedDescriptionKey: msg}];
    if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailInAppPurchase:error:)]) {
        [self.delegate dmAdManager:nil didFailInAppPurchase:transaction.payment.productIdentifier error:error];
    }
}

- (void)computeInpurchaseReceipt_type:(NSString *)receipt_type productId:(NSString *)productId transaction_id:(NSString *)transaction_id {
    if ([_productId isEqualToString:productId]) {
        if (![receipt_type isEqualToString:kSANDBOX]) {
            [self adjsut_RevenueProductId:productId transaction_id:transaction_id];
        }
        _productId = @"";
    }
}

- (void)adjsut_RevenueProductId:(NSString *)productId transaction_id:(NSString *)transaction_id {
    // 读取配置与商品信息
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (![reader isConfigLoaded]) {
        [reader loadConfigFromBundle:@"sdk_config_mediation"]; // 与现有配置加载方式保持一致
    }

    DMAdjustConfig *adjCfg = [reader adjustConfig];
    NSString *eventToken = adjCfg.sdk_iap_revenue_token;
    if (eventToken.length == 0) {
        [IMLogUtils warning:IMLogTagIAP format:@"🛒 [IAP] Adjust Revenue 事件未配置，跳过上报"];
        return;
    }

    // 商品美元定价（来自配置）
    DMIAPProductConfig *productCfg = [reader productConfigForId:productId];
    NSString *usdPriceStr = productCfg.dollar_price ?: @"0.00";

    // 从系统商品信息获取本地价格与货币
    NSDictionary *skProductInfo = [[DMInAppPurchaseHandleManager shareInAppPurchaseHandleManager] skproductInfo:productId];
    NSString *currency = skProductInfo[@"currency"] ?: @"USD";
    NSString *localPriceStr = skProductInfo[@"price"] ?: @"0.00";
    NSString *productName = skProductInfo[@"title"] ?: @"";

    if (![self isStringAFloat:localPriceStr]) {
        localPriceStr = @"0.00";
    }
    double revenueLocal = [localPriceStr doubleValue];

    // 统一美元收入（优先使用配置中的美元定价）
    double revenueUSD = 0.0;
    if ([self isStringAFloat:usdPriceStr]) {
        revenueUSD = [usdPriceStr doubleValue];
    } else {
        // 如果货币就是 USD，则直接使用本地价格
        revenueUSD = [currency isEqualToString:@"USD"] ? revenueLocal : 0.0;
    }

    // 构建 Adjust 事件参数（全部作为 partner 参数）
    NSMutableDictionary<NSString *, NSString *> *params = [NSMutableDictionary dictionary];
    // 事件名称，示例为 “purchase 100 coins”，此处用商品名拼接，若无商品名则用 productId
    NSString *eventName = productName.length > 0 ? [NSString stringWithFormat:@"purchase %@", productName] : [NSString stringWithFormat:@"purchase %@", productId ?: @"unknown"];
    params[@"event_name"] = eventName;
    params[@"order_id"] = transaction_id ?: @"";       // 渠道订单号（此处用交易ID）
    params[@"order_p_id"] = transaction_id ?: @"";      // 平台订单号（iOS也用交易ID）
    params[@"product_id"] = productId ?: @"";
    params[@"product_name"] = productName ?: @"";
    params[@"product_usd"] = usdPriceStr ?: @"0.00";
    params[@"currency"] = currency ?: @"USD";
    params[@"revenue_float"] = [NSString stringWithFormat:@"%.2f", revenueLocal];
    params[@"revenue_usd"] = [NSString stringWithFormat:@"%.2f", revenueUSD];

#if ADJUST_SDK_AVAILABLE
    // 构建并上报 Adjust 事件，包含 setRevenue 与自定义参数
    ADJEvent *event = [[ADJEvent alloc] initWithEventToken:eventToken];
    [event setRevenue:revenueLocal currency:currency ?: @"USD"];
    [params enumerateKeysAndObjectsUsingBlock:^(NSString *key, NSString *obj, BOOL *stop) {
        [event addPartnerParameter:key value:obj ?: @""]; // 作为 Partner 参数上报
    }];
    [Adjust trackEvent:event];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] Adjust Revenue 事件上报完成: token=%@, revenue=%.2f %@, product=%@", eventToken, revenueLocal, currency, productId];
#else
    // 没有集成 Adjust SDK 时，记录日志并跳过
    [IMLogUtils warning:IMLogTagIAP format:@"🛒 [IAP] 未集成 Adjust SDK，无法上报 Revenue 事件"];
#endif
}

- (BOOL)isStringAFloat:(NSString *)string {
    NSScanner *scanner = [NSScanner scannerWithString:string];
    float value;
    return [scanner scanFloat:&value] && [scanner isAtEnd];
}

- (void)trackBillingRevenueEvent:(NSString *)productId transactionId:(NSString *)transactionId isRestore:(BOOL)isRestore {
    if (productId.length == 0) {
        [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] Billing_Revenue 事件打点失败: productId为空"];
        return;
    }
    
    // 获取商品信息（价格和货币）
    NSDictionary *productInfo = [[DMInAppPurchaseHandleManager shareInAppPurchaseHandleManager] skproductInfo:productId];
    NSString *currency = productInfo[@"currency"] ?: @"USD";
    NSString *priceString = productInfo[@"price"] ?: @"0.00";
    
    // 验证价格格式
    if (![self isStringAFloat:priceString]) {
        priceString = @"0.00";
    }
    // 转换为数值用于上报
    double revenueValue = [priceString doubleValue];
    
    // 统一标准美元收入 w_n_d_revenue
    double usdRevenue = 0.0;
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (![reader isConfigLoaded]) {
        [reader loadConfigFromBundle:@"sdk_config_mediation"];
    }
    if ([currency isEqualToString:@"USD"]) {
        usdRevenue = revenueValue;
    } else {
        DMIAPProductConfig *cfg = [reader productConfigForId:productId];
        NSString *usdPrice = cfg.dollar_price;
        if ([usdPrice isKindOfClass:[NSString class]] && [self isStringAFloat:usdPrice]) {
            usdRevenue = [usdPrice doubleValue];
        } else {
            usdRevenue = 0.0;
        }
    }
    
    // Billing_Revenue 内购收入事件打点
    NSDictionary *billingRevenueParams = @{
        @"w_order_id": transactionId ?: @"",
        @"w_type": [self getProductTypeString:productId],
        @"w_order_p_id": productId, // iOS使用商品ID作为订单标识
        @"w_product_id": productId,
        @"w_product_name": (productInfo[@"title"] ?: @""),
        @"w_transaction_id": transactionId ?: @"",
        @"w_is_restore": @((isRestore ? 1 : 0)),
        @"w_currency": currency,
        @"w_revenue": @((revenueValue)),
        @"w_n_d_revenue": @((usdRevenue)),
        @"w_isRenewal": @0,
        @"w_renewal_times": @0
    };
    [[DMThinkingManager sharedManager] thinkingTrackEventWithKey:@"Billing_Revenue" properties:billingRevenueParams];
    [IMLogUtils info:IMLogTagIAP format:@"🛒 [IAP] 事件打点: Billing_Revenue - 商品ID: %@, 价格: %@ %@, 交易ID: %@", productId, priceString, currency, transactionId ?: @""];
}

- (DMProductType)getProductType:(NSString *)productId {
    // 优先从缓存读取
    NSNumber *cachedType = self.productTypeCache[productId];
    if (cachedType) {
        return (DMProductType)[cachedType integerValue];
    }

    // 确保配置已加载
    DMConfigReader *reader = [DMConfigReader sharedInstance];
    if (![reader isConfigLoaded]) {
        [reader loadConfigFromBundle:@"sdk_config_mediation"]; // 失败也不影响后续兼容逻辑
    }

    // 通过配置读取器判断商品类型
    // 1) 消耗型
    for (DMIAPProductConfig *cfg in [reader consumableProducts] ?: @[]) {
        if ([cfg.productId isEqualToString:productId]) {
            self.productTypeCache[productId] = @(DMProductTypeConsumable);
            return DMProductTypeConsumable;
        }
    }
    // 2) 非消耗型
    for (DMIAPProductConfig *cfg in [reader nonConsumableProducts] ?: @[]) {
        if ([cfg.productId isEqualToString:productId]) {
            self.productTypeCache[productId] = @(DMProductTypeNonConsumable);
            return DMProductTypeNonConsumable;
        }
    }
    // 3) 订阅（按非消耗型处理）
    for (DMIAPProductConfig *cfg in [reader subscriptionProducts] ?: @[]) {
        if ([cfg.productId isEqualToString:productId]) {
            self.productTypeCache[productId] = @(DMProductTypeNonConsumable);
            return DMProductTypeNonConsumable;
        }
    }

    // 未命中配置，保持历史默认：按消耗型处理，避免阻断流程
    self.productTypeCache[productId] = @(DMProductTypeConsumable);
    return DMProductTypeConsumable;
}

- (NSString *)getProductTypeString:(NSString *)productId {
    DMProductType type = [self getProductType:productId];
    switch (type) {
        case DMProductTypeConsumable:
            return @"consumable";
        case DMProductTypeNonConsumable:
            return @"non_consumable";
        default:
            return @"unknown";
    }
}

- (void)savePurchaseRecord:(NSString *)productId {
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray *purchasedProducts = [[defaults arrayForKey:@"PurchasedProducts"] mutableCopy] ?: [NSMutableArray array];
        if (![purchasedProducts containsObject:productId]) {
            [purchasedProducts addObject:productId];
            [defaults setObject:purchasedProducts forKey:@"PurchasedProducts"];
            [defaults synchronize];
        }
    }
}

// 保存已恢复的非消耗型商品记录（持久化）
- (void)saveRestoredRecord:(NSString *)productId {
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray *restoredProducts = [[defaults arrayForKey:@"RestoredProducts"] mutableCopy] ?: [NSMutableArray array];
        if (![restoredProducts containsObject:productId]) {
            [restoredProducts addObject:productId];
            [defaults setObject:restoredProducts forKey:@"RestoredProducts"];
            [defaults synchronize];
        }
    }
}

- (void)clearPurchaseRecord:(NSString *)productId {
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray *purchasedProducts = [[defaults arrayForKey:@"PurchasedProducts"] mutableCopy];
        [purchasedProducts removeObject:productId];
        [defaults setObject:purchasedProducts forKey:@"PurchasedProducts"];
        [defaults synchronize];
    }
}

- (BOOL)isProductPurchased:(NSString *)productId {
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray *purchasedProducts = [defaults arrayForKey:@"PurchasedProducts"];
        return [purchasedProducts containsObject:productId];
    }
    return NO;
}

// 检查非消耗型商品是否已经恢复过（持久化检查）
- (BOOL)isProductRestored:(NSString *)productId {
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSArray *restoredProducts = [defaults arrayForKey:@"RestoredProducts"];
        return [restoredProducts containsObject:productId];
    }
    return NO;
}

// 添加清除重复订单标记的方法
- (void)clearDuplicateTransaction:(NSString *)transactionId {
    [self.duplicateTransactions removeObject:transactionId];
}

// 修改处理重复订单的方法
- (void)handleDuplicateTransaction:(NSString *)transactionId productId:(NSString *)productId {
    [self.duplicateTransactions addObject:transactionId];
    
    // 如果是非消耗型商品，确保购买记录正确并返回成功回调
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        [self savePurchaseRecord:productId];
        
        // 调用购买成功回调
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didSuccessInAppPurchase:transactionId:)]) {
            [self.delegate dmAdManager:nil didSuccessInAppPurchase:productId transactionId:transactionId];
        }
    } else {
        // 调用购买失败回调
        NSError *error = [NSError errorWithDomain:@"DMInAppPurchase" code:1001 userInfo:@{NSLocalizedDescriptionKey: @"订单重复，请勿重复购买"}];
        if (self.delegate && [self.delegate respondsToSelector:@selector(dmAdManager:didFailInAppPurchase:error:)]) {
            [self.delegate dmAdManager:nil didFailInAppPurchase:productId error:error];
        }
    }
}

// 检查恢复购买状态
- (BOOL)isRestoreInProgress {
    return _isRestoreInProgress;
}

// 清除会话中的恢复记录
- (void)clearSessionRestoreRecords {
    [self.restoredProductIds removeAllObjects];
}

// 清除所有非消耗型商品的本地购买记录（供全量恢复使用）
- (void)clearAllNonConsumablePurchaseRecords {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"PurchasedProducts"];
    [defaults synchronize];
}

// 清除特定商品的恢复记录（持久化）
- (void)clearRestoredRecord:(NSString *)productId {
    if ([self getProductType:productId] == DMProductTypeNonConsumable) {
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSMutableArray *restoredProducts = [[defaults arrayForKey:@"RestoredProducts"] mutableCopy];
        [restoredProducts removeObject:productId];
        [defaults setObject:restoredProducts forKey:@"RestoredProducts"];
        [defaults synchronize];
    }
}

// 清除所有恢复记录（持久化）
- (void)clearAllRestoredRecords {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults removeObjectForKey:@"RestoredProducts"];
    [defaults synchronize];
}

@end
